package com.xxc.smartcar.blueTooth;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.google.android.material.button.MaterialButton;
import com.google.android.material.switchmaterial.SwitchMaterial;
import com.xxc.smartcar.R;

@SuppressWarnings("ALL")
public class BlueToothCarActivity extends AppCompatActivity {
    private static final int SEND_DELAY = 100; // 长按发送间隔(毫秒)
    private static final int HOLD_DELAY = 3000; // 长按保持阈值(毫秒)

    // 指令常量
    private static final byte UP = 0x00;
    private static final byte DOWN = 0x01;
    private static final byte STOP = 0x02;
    private static final byte LEFT = 0x03;
    private static final byte RIGHT = 0x04;

    private static final byte AUTO = 0x10;  // 自动模式指令
    private static final byte MANUAL = 0x11; // 手动模式指令

    private static final byte LED_OFF = 0x30;      // 熄灭
    private static final byte LED_MARQUEE = 0x31;  // 跑马灯
    private static final byte LED_WATER = 0x32;    // 流水灯
    private static final byte LED_BLINK = 0x33;    // 闪烁灯
    private static final byte LED_BREATH = 0x34;   // 呼吸灯
    private static final byte LED_RAINBOW = 0x35;  // 彩虹循环
    private static final byte LED_CUSTOM = 0x36;   // 自定义模式

    // 速度控制常量 (0x40-0xA4对应速度0-100)
    private static final byte SPEED_BASE = 0x40;
    private static final byte DEFAULT_SPEED = 80;  // 默认速度80

    // 控件
    private Toolbar toolbar;
    private MaterialButton btnUp, btnDown, btnLeft, btnRight, btnStop, btnMode;
    private SwitchMaterial switchLed;
    private TextView tvCurrentState, tvConnectionStatus, tvBattery, tvTemp, tvHum, tvSpeedValue;
    private RadioGroup ledModeGroup;
    private SeekBar speedSeekbar;

    // 蓝牙与控制变量
    private BluetoothConnectionManager bluetoothManager;
    private Handler sendHandler;
    private Handler holdHandler;

    private boolean isSending = false;
    private boolean isAutoMode = false; // 默认手动模式
    private boolean isHolding = false;  // 是否处于长按保持状态
    private byte currentCommand = STOP; // 当前执行的指令
    private byte currentLedMode = LED_OFF; // 当前LED模式

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_car); // 加载布局

        // 初始化蓝牙管理器
        bluetoothManager = BluetoothConnectionManager.getInstance();
        if (!bluetoothManager.isConnected()) {
            Toast.makeText(this, "蓝牙未连接", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        initView();
        setupListeners();
        initHandlers();

        // 初始化速度为80
        sendSpeedCommand(DEFAULT_SPEED);
        tvSpeedValue.setText(DEFAULT_SPEED + "%");
        speedSeekbar.setProgress(DEFAULT_SPEED);

        // 初始化模式显示和指令发送（默认手动模式）
        updateModeDisplay();
        sendCommand(MANUAL); // 发送手动模式指令

        // 初始化LED模式选择器，默认选中"跑马灯"
        ledModeGroup.check(R.id.led_mode_2);
        currentLedMode = LED_MARQUEE;
    }

    /**
     * 初始化控件
     */
    private void initView() {
        // 顶部标题栏
        toolbar = findViewById(R.id.toolbar);

        // 状态卡片文本
        tvCurrentState = findViewById(R.id.current_state);
        tvConnectionStatus = findViewById(R.id.connection_status);
        tvBattery = findViewById(R.id.battery_level);
        tvTemp = findViewById(R.id.tv_temp);
        tvHum = findViewById(R.id.tv_hum);

        // 控制按钮
        btnMode = findViewById(R.id.btn_mode);
        switchLed = findViewById(R.id.switch_led);
        ledModeGroup = findViewById(R.id.led_mode_group);

        // 速度控制
        speedSeekbar = findViewById(R.id.speed_seekbar);
        tvSpeedValue = findViewById(R.id.speed_value);

        // 方向控制按钮
        btnUp = findViewById(R.id.btn_up);
        btnDown = findViewById(R.id.btn_down);
        btnLeft = findViewById(R.id.btn_left);
        btnRight = findViewById(R.id.btn_right);
        btnStop = findViewById(R.id.btn_stop);
    }

    /**
     * 设置所有控件监听
     */
    private void setupListeners() {
        // 标题栏点击跳转蓝牙连接页
        toolbar.setOnClickListener(v -> {
            startActivity(new Intent(BlueToothCarActivity.this, BlueToothConnectActivity.class));
            finish();
        });

        // 方向按钮监听（长按5秒后保持状态）

        setupDirectionListener(btnUp, UP, "前进");
        setupDirectionListener(btnDown, DOWN, "后退");
        setupDirectionListener(btnLeft, LEFT, "左转");
        setupDirectionListener(btnRight, RIGHT, "右转");
        // 停止按钮监听
        btnStop.setOnClickListener(v -> {
            stopCurrentAction();
        });

        // 模式切换按钮（自动/手动）
        btnMode.setOnClickListener(v -> {
            isAutoMode = !isAutoMode;
            updateModeDisplay(); // 更新显示
            sendCommand(isAutoMode ? AUTO : MANUAL); // 发送模式指令
            if (isAutoMode) {
                stopCurrentAction(); // 切换到自动模式时停止当前动作
            }
        });

        // LED模式选择监听
        ledModeGroup.setOnCheckedChangeListener((group, checkedId) -> {
            if (checkedId == R.id.led_mode_1) { // 熄灭
                currentLedMode = LED_OFF;
            } else if (checkedId == R.id.led_mode_2) { // 跑马灯
                currentLedMode = LED_MARQUEE;
            } else if (checkedId == R.id.led_mode_3) { // 流水灯
                currentLedMode = LED_WATER;
            } else if (checkedId == R.id.led_mode_4) { // 闪烁灯
                currentLedMode = LED_BLINK;
            } else if (checkedId == R.id.led_mode_5) { // 呼吸灯
                currentLedMode = LED_BREATH;
            } else if (checkedId == R.id.led_mode_6) { // 彩虹循环
                currentLedMode = LED_RAINBOW;
            } else if (checkedId == R.id.led_mode_7) { // 自定义模式
                currentLedMode = LED_CUSTOM;
            }
            // 发送LED模式指令
            sendCommand(currentLedMode);
            // 同步更新开关状态
            switchLed.setChecked(currentLedMode != LED_OFF);
        });

        // LED开关监听
        switchLed.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                // 打开时发送当前选中的模式
                if (currentLedMode == LED_OFF) {
                    currentLedMode = LED_MARQUEE;
                    ledModeGroup.check(R.id.led_mode_2);
                }
                sendCommand(currentLedMode);
            } else {
                // 关闭时发送熄灭指令
                sendCommand(LED_OFF);
            }
        });

        // 速度控制监听
        speedSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    tvSpeedValue.setText(progress + "%");
                    sendSpeedCommand(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {}

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {}
        });
    }

    /**
     * 初始化处理器
     */
    private void initHandlers() {
        // 用于发送连续指令的Handler
        sendHandler = new Handler(msg -> {
            if (isSending && !isAutoMode && !isHolding) {
                byte cmd = (byte) msg.what;
                sendCommand(cmd);
                sendHandler.sendEmptyMessageDelayed(cmd, SEND_DELAY);
            }
            return true;
        });

        // 用于检测长按保持的Handler
        holdHandler = new Handler(msg -> {
            if (isSending && !isAutoMode) {
                isHolding = true;
                isSending = false;
                sendHandler.removeCallbacksAndMessages(null);
                Toast.makeText(BlueToothCarActivity.this, "已保持状态", Toast.LENGTH_SHORT).show();
            }
            return true;
        });
    }

    /**
     * 方向按钮触摸监听（长按5秒后保持状态）
     */
    private void setupDirectionListener(MaterialButton button, final byte command, final String stateText) {
        button.setOnTouchListener((v, event) -> {
            if (isAutoMode || isHolding) {
                // 自动模式或已处于保持状态时忽略触摸事件
                return true;
            }

            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    currentCommand = command;
                    isSending = true;
                    sendCommand(command);
                    tvCurrentState.setText(stateText);
                    // 发送连续指令
                    sendHandler.sendEmptyMessageDelayed(command, SEND_DELAY);
                    // 启动长按保持计时器
                    holdHandler.sendEmptyMessageDelayed(command, HOLD_DELAY);
                    break;

                case MotionEvent.ACTION_UP:
                case MotionEvent.ACTION_CANCEL:
                    // 如果还没进入保持状态，释放时停止
                    if (!isHolding) {
                        isSending = false;
                        sendHandler.removeCallbacksAndMessages(null);
                        holdHandler.removeCallbacksAndMessages(null);
                        sendCommand(STOP);
                        tvCurrentState.setText("停止");
                        currentCommand = STOP;
                    }
                    break;
            }
            return true;
        });
    }

    /**
     * 停止当前动作
     */
    private void stopCurrentAction() {
        if (isAutoMode) return;

        // 发送停止指令
        sendCommand(STOP);
        tvCurrentState.setText("停止");

        // 重置状态变量
        isSending = false;
        isHolding = false;
        currentCommand = STOP;

        // 清除所有消息
        sendHandler.removeCallbacksAndMessages(null);
        holdHandler.removeCallbacksAndMessages(null);
    }

    /**
     * 更新模式显示状态
     */
    private void updateModeDisplay() {
        if (isAutoMode) {
            btnMode.setText("自动模式");
            tvCurrentState.setText("自动");
            // 自动模式下禁用方向按钮和速度控制
            setDirectionButtonsEnabled(false);
            speedSeekbar.setEnabled(false);
        } else {
            btnMode.setText("手动模式");
            tvCurrentState.setText("停止");
            // 手动模式下启用方向按钮和速度控制
            setDirectionButtonsEnabled(true);
            speedSeekbar.setEnabled(true);
        }
    }

    /**
     * 启用/禁用方向控制按钮
     */
    private void setDirectionButtonsEnabled(boolean enabled) {
        btnUp.setEnabled(enabled);
        btnDown.setEnabled(enabled);
        btnLeft.setEnabled(enabled);
        btnRight.setEnabled(enabled);
        btnStop.setEnabled(enabled);
    }

    /**
     * 发送指令到蓝牙
     */
    private void sendCommand(byte command) {
        if (bluetoothManager.isConnected()) {
            bluetoothManager.sendData(new byte[]{command});
        } else {
            Toast.makeText(this, "蓝牙已断开", Toast.LENGTH_SHORT).show();
            finish();
        }
    }

    /**
     * 发送速度指令
     */
    private void sendSpeedCommand(int speed) {
        // 速度范围限制在0-100
        int clampedSpeed = Math.max(0, Math.min(100, speed));
        // 转换为指令格式 (0x40-0xA4)
        byte speedCommand = (byte) (SPEED_BASE + clampedSpeed);
        sendCommand(speedCommand);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 清理所有消息
        sendHandler.removeCallbacksAndMessages(null);
        holdHandler.removeCallbacksAndMessages(null);
        // 发送停止指令
        sendCommand(STOP);
        sendCommand(LED_OFF);
    }
}
